import os
import time
import random
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
import tkinter as tk
from tkinter import messagebox, ttk, scrolledtext

# 保存路径
SAVE_PATH = r"F:\起点中文网爬取的小说"

# 创建保存路径
if not os.path.exists(SAVE_PATH):
    os.makedirs(SAVE_PATH)

# 初始化Edge WebDriver
def init_driver():
    options = webdriver.EdgeOptions()
    options.add_argument('--disable-blink-features=AutomationControlled')  # 禁用自动化控制特征
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    options.add_argument('--start-maximized')  # 最大化窗口
    options.add_argument('--disable-infobars')  # 禁用信息栏
    options.add_argument('--disable-extensions')  # 禁用扩展
    options.add_argument('--disable-gpu')  # 禁用GPU加速
    options.add_argument('--disable-logging')  # 禁用日志
    options.add_argument('--log-level=3')  # 设置日志级别
    options.add_argument('--ignore-certificate-errors')  # 忽略证书错误
    options.add_argument('--ignore-ssl-errors')  # 忽略SSL错误
    options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.59')  # 设置User-Agent

    service = Service(executable_path=r'D:\python\msedgedriver.exe')  # 替换为你的EdgeDriver路径
    driver = webdriver.Edge(service=service, options=options)
    return driver

# 模拟人类行为
def human_like_behavior(driver):
    # 随机移动鼠标
    window_size = driver.get_window_size()
    for _ in range(5):
        x = random.randint(0, window_size['width'])
        y = random.randint(0, window_size['height'])
        driver.execute_script(f"window.scrollTo({x}, {y});")
        time.sleep(random.uniform(0.5, 1.5))

# 搜索小说
def search_novel():
    keyword = entry.get()
    if not keyword:
        messagebox.showwarning("警告", "请输入搜索关键词！")
        return

    url = f"https://www.qidian.com/so/{keyword}.html"
    try:
        driver.get(url)
        time.sleep(5)  # 等待页面加载
        human_like_behavior(driver)  # 模拟人类行为

        # result_text.delete(1.0, tk.END)  # 清空文本框
        page_num = 1
        while True:
            WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'book-mid-info')))
            soup = BeautifulSoup(driver.page_source, 'html.parser')
            novels = soup.find_all('div', class_='book-mid-info')

            for novel in novels:
                title = novel.find('h3').get_text(strip=True)
                author = novel.find('p', class_='author').get_text(strip=True)
                link = novel.find('h3').find('a')['href']
                full_link = f"https:{link}"
                result_text.insert("", "end", values=(title, author, full_link))

            # 检查是否有下一页
            next_button = driver.find_elements(By.CSS_SELECTOR, 'a.lbf-pagination-next')
            if not next_button or 'disabled' in next_button[0].get_attribute('class'):
                break  # 如果没有下一页，退出循环

            # 点击下一页
            next_button[0].click()
            time.sleep(5)  # 等待页面加载
            human_like_behavior(driver)  # 模拟人类行为
            page_num += 1

        messagebox.showinfo("成功", f"搜索完成，共 {page_num} 页！")
    except Exception as e:
        messagebox.showerror("错误", f"搜索失败: {e}")

# 下载小说
def download_novel():
    selected_novel = result_text.selection()
    if selected_novel == ():
        messagebox.showwarning("警告", "请选择要下载的小说！")
        return
    for selected in selected_novel:

        link = result_text.item(selected)["values"][2]
        # print(link)
        try:
            driver.get(link)
            time.sleep(5)  # 等待页面加载
            human_like_behavior(driver)  # 模拟人类行为
            WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'volume-chapters')))
            novel_soup = BeautifulSoup(driver.page_source, 'html.parser')

            title = novel_soup.find('div', class_='book-info').find('h1').get_text(strip=True)
            chapters = novel_soup.find_all('li', class_='chapter-item')
            novel_content = ""
            for chapter in chapters:
                chapter_url = f"https:{chapter.find('a')['href']}"
                driver.get(chapter_url)
                time.sleep(2)  # 等待页面加载
                human_like_behavior(driver)  # 模拟人类行为
                WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'content mt-1.5em text-s-gray-900 leading-[1.8] relative z-0 r-font-black lock-mask')))
                chapter_soup = BeautifulSoup(driver.page_source, 'html.parser')
                selected_content = chapter_soup.select('#c-402733549 > p:nth-child > span.content-text')
                print(selected_content)
                # for content in selected_content:
                #
                #     novel_content += f"{chapter.get_text(strip=True)}\n{content.get_text(strip=True)}\n\n"
                #
                #
                #     print(novel_content)

            # file_path = os.path.join(SAVE_PATH, f"{title}.txt")
            # with open(file_path, 'w', encoding='utf-8') as f:
            #     f.write(novel_content)
            # messagebox.showinfo("成功", f"小说《{title}》下载完成！")
        except Exception as e:
            messagebox.showerror("错误", f"下载失败: {e}")

# 创建UI界面
root = tk.Tk()
root.title("起点中文网小说下载器")

frame = ttk.Frame(root, padding="10")
frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))

label = ttk.Label(frame, text="搜索关键词:")
label.grid(row=0, column=0, sticky=tk.W)

entry = ttk.Entry(frame, width=50)
entry.grid(row=0, column=1, sticky=(tk.W, tk.E))

search_button = ttk.Button(frame, text="搜索", command=search_novel)
search_button.grid(row=0, column=2, sticky=tk.W)

# 数据表格
columns = ('title', 'author', 'link')
result_text = ttk.Treeview(frame, columns=columns, show='headings')
result_text.column('title', width=100, anchor='center')
result_text.heading('title', text='书名')
result_text.column('author', width=150, anchor='center')
result_text.heading('author', text='作者')
result_text.column('link', width=260, anchor='w')
result_text.heading('link', text='链接')
result_text.grid(row=1, column=0, columnspan=3, pady=10)

# 数据表加滚动条
scrollbar = ttk.Scrollbar(root, orient=tk.VERTICAL, command=result_text.yview)
result_text.configure(yscroll=scrollbar.set)
scrollbar.grid(row=0, column=1, sticky='ns')

download_button = ttk.Button(frame, text="下载", command=download_novel)
download_button.grid(row=2, column=1, pady=10)

# 初始化WebDriver
driver = init_driver()

# 运行主循环
root.mainloop()

# 关闭WebDriver
driver.quit()